package com.pervasa.demo.re.impl.data;

import org.osgi.framework.ServiceReference;

import com.pervasa.atlas.dev.service.AtlasService;
import com.pervasa.demo.re.impl.ReactivityEngine;

/**
 * Dealing with the atomic event which directly related to values.
 * 
 * @author Xiaoyang Gao
 */
public class AtomicEvent extends Event {
	private String name;

	private AtlasService sensor;
	private int[] range = new int[2];
	private ReactivityEngine env;

	public AtomicEvent(String name, AtlasService sensor, int lowerBound, int upperBound, ReactivityEngine env) {
		super(name);
		this.sensor = sensor;
		this.range[0] = lowerBound;
		this.range[1] = upperBound;
		this.env = env;
		env.getSensorListenerMap().get(sensor).add(this);
	}
	
	public String getExpression() {
		return ((ServiceReference) env.getSenserRefMap().get(sensor)).getProperty("Node-Id").toString() + ((range[0] == range[1]) ? "(" + range[0] + ")" : "[" + range[0] + ", " + range[1] + "]"); 
	}

	public String toString() {
		return name
				+ ": " + ((ServiceReference) env.getSenserRefMap().get(sensor)).getProperty("Node-Id")
				+ ((range[0] == range[1]) ? ("(" + range[0] + ")") : ("["
						+ range[0] + ", " + range[1] + "[")) + " IsTriggered: "
				+ isTriggered() + " Time: " + getStartTime();
	}

	@Override
	public void evaluate(Object arg) {
		int value = ((Integer) arg).intValue();
		boolean result = false;
		if (value >= range[0] && value <= range[1]) {
			result = true;
		}
		
		setTriggered(result);
	}
}